﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Data.Odbc;
using System.Threading;
using Common;
using Common.Extension;
using GxTsSharp.Models;
using log4net;
using Newtonsoft.Json;

namespace StockIndex.service
{
    //股票市值service
    public class StockMarketService
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(StockMarketService));

        public static void FullStockMarket()
        {
            //股票代码(000001.SZ)=》流通股（万股）
            Dictionary<String, Decimal> stockCodeCirculationUnitDic = new Dictionary<string, decimal>();
            //流通股（万股）
            var strCon = @"Driver={Microsoft dBase Driver (*.dbf)};DefaultDir=" + $@"{Config.TdxPath}\T0002\hq_cache";
//            var strCon = @"Driver={Microsoft dBase Driver (*.dbf)};DefaultDir=D:\new_tdx\T0002\hq_cache";

            using (OdbcDataAdapter adapter = new OdbcDataAdapter("select * from base.dbf", strCon))
            {
                DataTable dtData = new DataTable();
                adapter.Fill(dtData);

                foreach (DataRow dr in dtData.Rows)
                {
                    string market =
                        dr["SC"].ToString().Trim() == "0" ? "SZ" : (dr["SC"].ToString().Trim() == "1" ? "SH" : "?");
                    String stockCode = dr["GPDM"].ToString().Trim();
                    string updateDate = dr["GXRQ"].ToString().Trim();
                    Decimal circulationUnit = Convert.ToDecimal(dr["LTAG"].ToString());
                    stockCodeCirculationUnitDic.Put($"{stockCode}.{market}", circulationUnit);
                }
            }

            if (stockCodeCirculationUnitDic.Count == 0)
            {
                //todo 告警
                Log.Error("没法获取股本数据");
                throw new Exception("没法获取股本数据");
            }

            int tryCount = 0;
            while (!Program.FinsihEagleInit)
            {
                if (tryCount >= 20)
                {
                    Log.Error("初始数据长时间不成功");
                    throw new Exception("初始数据长时间不成功");
                }

                tryCount++;
                Thread.Sleep(3000);
                Log.Warn("eagle 尚未准备完毕");
            }

            foreach (var kv in Program.Eagle.DicStockInfo)
            {
                var marketId = kv.Key;
                List<StockInfo> listStock = kv.Value;
                var strMarketId = kv.Key == EMarketID.Market_SH ? "SH" : (kv.Key == EMarketID.Market_SZ ? "SZ" : "?");
                foreach (StockInfo s in listStock)
                {
                    var firstNum = s.Code.Substring(0, 1);
                    if ((marketId == EMarketID.Market_SH && firstNum == "6") ||
                        (marketId == EMarketID.Market_SZ && (firstNum == "0" || firstNum == "3")))
                    {
                        var price = Convert.ToDecimal(s.PrevClose);
                        if (price == 0)
                        {
                        }

                        if (stockCodeCirculationUnitDic.ContainsKey($"{s.Code}.{strMarketId}"))
                        {
                            var volume = stockCodeCirculationUnitDic[$"{s.Code}.{strMarketId}"];
                            var marketValue = price * volume / 10000;
                            MemoryDataDB.AddOrUpDateStockMarketValue($"{s.Code}.{strMarketId}", marketValue);
                        }
                    }
                }
            }

//            Log.Debug(JsonConvert.SerializeObject(MemoryDataDB.DicStockMarketValueYd));
        }

        //主题的各个权重
        public static void FullTopicWeight()
        {
            if (MemoryDataDB.DicStockMarketValueYd.IsEmpty)
            {
                FullStockMarket();
                if (MemoryDataDB.DicStockMarketValueYd.IsEmpty)
                {
                    Log.Error("股票市值没数据");
                    throw new Exception("股票市值没数据");
                }
            }

            if (MemoryDataDB.TopicStocks.IsEmpty)
            {
                MainTopicService.FullTopicStocks();
                if (MemoryDataDB.TopicStocks.IsEmpty)
                {
                    {
                        Log.Error("主题没有股票数据");
                        throw new Exception("主题没有股票数据");
                    }
                }

            }
            
            foreach (var topicStock in MemoryDataDB.TopicStocks)
            {
                String topicName = topicStock.Key;
                HashSet<String> stockCodeSet = topicStock.Value;
                
                var dic = new Dictionary<string, decimal>();
                decimal sumMarketValue = 0m;
                foreach (var stockCode in stockCodeSet)
                {
                    //var marketValue = RedisController.GetMarketValue(stockCode);
                    var marketValue = MemoryDataDB.GetMarketValue(stockCode);
                    dic.Add(stockCode, marketValue);
                    sumMarketValue += marketValue;
                }

                if (sumMarketValue == 0)
                {
                    Log.Error($"{topicName} 总市值为0");
                    continue;
                }

                foreach (var lkv in dic)
                {
                    var stockCode = lkv.Key;
                    var marketValue = lkv.Value;
                    var weight = marketValue / sumMarketValue;
                    MemoryDataDB.AddOrUpdateTopicStockWeight(topicName, stockCode,
                        weight);
                }
            }

        }
    }
}